package com.baiduspring.web.user;


import com.baiduspring.dao.entity.User;
import com.baiduspring.error.BaiduSpringException;
import com.baiduspring.service.user.PrivateLetterService;
import com.baiduspring.utils.ResponseResult;
import com.baiduspring.utils.SystemCode;
import com.baiduspring.vo.PrivateLetteVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 私信发送控制器
 *
 * @author xiongyan
 */
@RestController
@RequestMapping(value = "/private_letter")
@Scope(value = "prototype")
@Slf4j
public class PrivateLetterController {
    @Resource
    private PrivateLetterService privateLetterService;

    @PostMapping(value = "/send")
    public ResponseResult send(HttpServletRequest request, PrivateLetteVO vo) {
        ResponseResult result = new ResponseResult<>();

        Object o = request.getSession().getAttribute("user");
        if (Objects.isNull(o)) {
            result.setCode(SystemCode.FAIL);
            result.setMessage("登录失效，请先登录...");
            return result;
        }

        User user = (User) o;

        try {
            vo.setSender(user.getAccount());
            privateLetterService.create(vo.validate());

            result.setCode(SystemCode.SUCCESS);
            result.setMessage("私信发送成功");
        } catch (BaiduSpringException e) {
            result.setCode(SystemCode.FAIL);
            result.setMessage(e.getErrorMsg());
        }

        return result;
    }

    @GetMapping(value = "/count")
    public Integer getPrivateLetterCount(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        return privateLetterService.getCount(user.getAccount(), 0);
    }
}
